// 初始化测试数据库的脚本
const { exec } = require('child_process');
const path = require('path');

// 设置测试环境变量
process.env.NODE_ENV = 'test';

// 引入统一配置模块
const config = require('../config/config');

// 从统一配置获取数据库配置
const dbHost = config.db.host;
const dbPort = config.db.port;
const dbUser = config.db.username;
const dbPass = config.db.password;
const dbName = config.db.database;

console.log('正在创建测试数据库:', dbName);
console.log('数据库配置:', `${dbHost}:${dbPort}`);
console.log('当前环境:', config.env);

// 创建测试数据库的SQL命令
const createDbCommand = `mysql -h ${dbHost} -P ${dbPort} -u ${dbUser} -p${dbPass} -e "CREATE DATABASE IF NOT EXISTS \`${dbName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"`;

exec(createDbCommand, (error, stdout, stderr) => {
  if (error) {
    console.error('创建测试数据库时出错:', error.message);
    console.error(`请确保MySQL服务在 ${dbHost}:${dbPort} 运行`);
    console.error('数据库配置信息:', {
      host: dbHost,
      port: dbPort,
      user: dbUser,
      database: dbName
    });
    process.exit(1);
    return;
  }
  
  if (stderr) {
    console.error('stderr:', stderr);
    return;
  }
  
  console.log('测试数据库创建成功:', dbName);
  console.log('标准输出:', stdout);
});